import { Button, Input, message } from "antd";
import login_style from "./index.module.less";
import { useNavigate, Navigate } from "react-router-dom";
import globalStore from "../../store/globalStore";
import request from "../../api";

interface input {
  username: string;
  password: string;
}

const { reqLogin } = request;
export default function login() {
  const router = useNavigate();
  const input: input = {
    username: "",
    password: "",
  };
  if (localStorage.getItem("token")) {
    return <Navigate to="/"></Navigate>;
  }
  return (
    <div className={login_style.main}>
      <div className={login_style.login_box}>
        <h1>登录</h1>
        <Input
          placeholder="账号"
          onInput={({ target }) => {
            input.username = (target as HTMLInputElement).value;
          }}
        />
        <Input
          placeholder="密码"
          type="password"
          onInput={({ target }) => {
            input.password = (target as HTMLInputElement).value;
          }}
        />
        <Button
          type="primary"
          onClick={async () => {
            const { password, username } = input;
            if (password && username) {
              const result = (await reqLogin(username, password)) as unknown;
              if (result instanceof Array && result[0]) {
                localStorage.setItem("token", result[0].roleId);
                await globalStore.actions.changeUserName(result[0].username);
                localStorage.setItem("userRegion", result[0].region);
                globalStore.data.userRegion = result[0].region;
                message.success("登录成功");
                router("/");
              } else {
                message.error("账号或密码错误");
              }
            } else {
              message.error("请检查账号或者密码是否空置");
            }
          }}
        >
          点击登录
        </Button>
      </div>
    </div>
  );
}
